<?php
/**
 * 视图处理
 * @copyright 2020-2021 WillPHP
 * @author NoMind<24203741@qq.com/113344.com>
 * @version WillPHPv3
 * @since 2021-12-01
 */
namespace wiphp;
defined('WIPHP_URI') or die('Access Denied');
class View {
	protected static $vars = [];
	//模板转变量
	public static function assign($name = '', $value = null) {
		if (is_array($name)) {
			self::$vars = array_merge(self::$vars, $name);
			return true;
		} else if (!empty($name)) {
			self::$vars[$name] = $value;
			return true;
		}	
		return false;
	} 
	//模板渲染显示
	public static function fetch($template = '', $vars = []) {
		if (!empty($vars)) self::$vars = array_merge(self::$vars, $vars);	
		$viewfile = self::getViewFile($template);
		if (!file_exists($viewfile)) {
			App::halt(basename($viewfile).'模板文件不存在。');
		}
		array_walk_recursive(self::$vars, 'self::parseVars'); //输出前处理
		define('__RUNTIME__', round((microtime(true) - START_TIME) , 4));	
		Template::render($viewfile, self::$vars);		
	}
	//获取当前控制器操作的模板路径
	protected static function getViewFile($file = '') {
		$path = __MODULE__;
		if ($file == '') {
			$file = __ACTION__;
		} elseif (strpos($file, ':')) {
			list($path, $file) = explode(':', $file);
		} elseif (strpos($file, '/')) {
			$path = '';
		}
		$path = strtolower($path);
		$pathfile = ltrim($path.'/'.$file, '/').'.html';
		$viewfile = PATH_VIEW.'/'.$pathfile;
		if (THEME_ON) {
			$viewfile = PATH_VIEW.'/'.__THEME__.'/'.$pathfile;
			if (file_exists($viewfile)) $viewfile = PATH_VIEW.'/default/'.$pathfile;
		}
		return $viewfile;
	}
	//变量输出前处理
	protected static function parseVars(&$value, $key) {
		$value = stripslashes($value); //删除反斜杠
	}
}